/**
 * This file is part of Aurea development project.
 * This source code is CopyRight of Juan-Rafael Bautista and
 * will never be used for comercial objectives.
 *
 */
package es.aurea.menu.creator.sources;

import es.aurea.menu.creator.jaxbfiles.Menu;
import es.aurea.menu.creator.jaxbfiles.MenuElement;
import es.aurea.presentation.security.Security;
import es.aurea.presentation.utils.EJBLocator;
import es.aurea.transferobjects.UserTO;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 * <b>Description: </b> 
 * @author Juan-Rafael Bautista
 * @date 12-jun-2009
 */
public class MenuBuilder {


    private List<Element> securedMenu = new ArrayList<Element>();
    private Logger logger = Logger.getLogger(this.getClass().getName());

    private UserTO oldUser=null;
    private int counter = 0 ;

    public List<Element> getMenu() {

        UserTO user = null;
        Security security = (Security) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("Security");

        if (security == null) {
            logger.severe("]-------> " +"SecurityBean is null");
            user = new UserTO();
            user.setGroupoName(0, "public");
        } else if (!security.getIsUserLogued()) {
            logger.finest("]-------> " +"User not logued");
            user = new UserTO();
            user.setGroupoName(0, "public");
        } else {
            logger.finest("]-------> " +"User " + security.getUserName() + " logued");
            user = security.getUser();
        }

        if (user.equals(oldUser) && securedMenu!=null){
            return securedMenu;
        }

        oldUser = new UserTO();
        oldUser.copy(user);
        
        securedMenu = new ArrayList<Element>();

        try {
            InputStream is = this.getClass().getResourceAsStream("MenuCreatorFile.xml");
            if (is == null) {
                logger.severe("]-------> " +"No se ha podido encontrar el fichero MenuCreatorFile.xml");
                return null;
            }
            Unmarshaller unmarshaller = JAXBContext.newInstance(Menu.class).createUnmarshaller();

            Menu menu = (Menu) unmarshaller.unmarshal(is);

            for (MenuElement element :menu.getMainElement()) {

                if (matches(user, element.getGroups()) != null ){
                    securedMenu.add(new Element(element,element));

                    if (element.getSubElement() != null && element.getSubElement().size()!=0){
                        readElement(user, element);
                    }
                }

            }

            return securedMenu;

        } catch (JAXBException ex) {
            Logger.getLogger(MenuBuilder.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * <b>Description: </b> Determina si el usuario tiene permisos para este grupo,
     * devuelve el nombre del grupo en caso de tenerlos, devuelve null en caso de no tenerlos.
     * @author Juan-Rafael Bautista
     * @date 12-jun-2009
     * */
    private String matches(UserTO user, String groups) {
        String result = "";
        Set set = user.getGroupsCollection().entrySet();
        Iterator iter = set.iterator();

        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String usergroup = (String) entry.getValue();

            if (groups!=null && groups.contains(usergroup)) {
                result+= usergroup;
            }
        }
        return result.equals("")?null:result;

    }

    /**
     * <b>Description: </b> Lee los elementos y monta el menu
     * @author Juan-Rafael Bautista
     * @date 12-jun-2009
     * */
    private void readElement(UserTO user, MenuElement father){

            for (MenuElement element : father.getSubElement()) {

                if (matches(user, element.getGroups()) != null ){
                    securedMenu.add(new Element(father, element));
                    
                    if (element.getSubElement() != null && element.getSubElement().size()!=0){
                        readElement(user, element);
                    }
                }

            }

    }
}
